import { v4 as uuidv4 } from 'uuid'

const tableMap = {}
const requireTables = require.context('./tables', true, /\.js$/)
requireTables.keys().forEach((fileName) => {
  tableMap[fileName.split('/').pop().split('.')[0]] = requireTables(fileName).default
})

const treeMap = {}
const requireTrees = require.context('./trees', true, /\.js$/)
requireTrees.keys().forEach((fileName) => {
  treeMap[fileName.split('/').pop().split('.')[0]] = requireTrees(fileName).default.data
})

const dicMap = {}
const requireDics = require.context('./dictionaries', true, /\.js$/)
requireDics.keys().forEach((fileName) => {
  dicMap[fileName.split('/').pop().split('.')[0]] = requireDics(fileName).default.data
})

export default {
  query (url, params) {
    if (url === '/tree/data') {
      // 树
      return treeMap[params.treeConfigId]
    } else if (url === '/grid/getColumnsData') {
      // 列信息
      const table = tableMap[params.metaSet]
      const columns = table.columns
      for (const c of columns.filter(c => c.cellType === 'dic' && c.dictionaryKey)) {
        c.cellProp = c.field + '_TEXT'
      }
      return { columns: columns.concat((table.formItems || []).filter(i => i.isKey === '1')), searchs: table.conditions || [] }
    } else if (url === '/grid/getTableData') {
      // 表格数据
      const table = tableMap[params.metaSet]
      const methodParams = JSON.parse(params.methodParams)
      let fullData = table.data
      // 简单查询条件过滤
      if (methodParams.simpleQueryParam) {
        for (const item of methodParams.simpleQueryParam) {
          fullData = fullData.filter(r => {
            if (item.fieldValueRel === 'like') {
              return r[item.field].includes(item.value)
            } else if (item.fieldValueRel === 'eq') {
              return item.value.split(',').includes(r[item.field])
            }
            return false
          })
        }
      }
      // 查询详情
      if (methodParams.queryParam) {
        for (const [key, value] of Object.entries(methodParams.queryParam)) {
          fullData = fullData.filter(r => r[key] === value)
        }
      }
      let data = []
      // 分页
      if (params.pageSize) {
        const startIndex = (params.pageNum - 1) * params.pageSize
        data = fullData.slice(startIndex, startIndex + params.pageSize)
      } else {
        data = fullData.slice()
      }
      let rows = []
      // 字典处理
      const dictionaryColumns = table.columns.filter(c => c.cellType === 'dic' && c.dictionaryKey)
      if (dictionaryColumns.length) {
        for (const r of data) {
          const row = { ...r }
          for (const c of dictionaryColumns) {
            row[c.field + '_TEXT'] = dicMap[c.dictionaryKey].find(d => d.value === r[c.field])?.label
          }
          rows.push(row)
        }
      } else {
        rows = data
      }
      return {
        rows,
        total: fullData.length
      }
    } else if (url === '/dic/compareReleaseTime') {
      // 字典过期处理
      return Object.keys(dicMap)
    } else if (url === '/dic/getDicData') {
      // 字典数据
      return { rows: dicMap[params.dicKey] }
    } else if (url === '/form/getItemsData') {
      // 表单项
      return {
        items: tableMap[params.metaSet].formItems.map(i => ({
          ...i,
          visible: i.visible === undefined ? '1' : i.visible,
          isInsert: i.isInsert === undefined ? '1' : i.isInsert,
          isEdit: i.isEdit === undefined ? '1' : i.isEdit
        }))
      }
    } else if (url === '/SingleTable/curd') {
      // 新增、修改、删除
      const table = tableMap[params.metaSet]
      const model = JSON.parse(params.methodParams)
      const idProp = table.formItems.find(i => i.isKey === '1')?.field
      if (params.methodCode === 'insert') {
        model.id = uuidv4()
        table.data.unshift(model)
        return Promise.resolve(model)
      } else if (params.methodCode === 'update') {
        const row = table.data.find(r => r[idProp] === model[idProp])
        Object.assign(row, model)
        return Promise.resolve(row)
      } else if (params.methodCode === 'delete') {
        const index = table.data.findIndex(r => r[idProp].toString() === model[idProp])
        table.data.splice(index, 1)
      }
    } else {
      // debugger
    }
  }
}
